package com.kusiri.kframework
{

 	import flash.events.Event;
 	import flash.events.EventDispatcher;
 	import flash.net.URLLoader;
 	import flash.net.URLRequest;
 	import flash.system.ApplicationDomain;
 	
 	/**
 	 * This is the bootstrapper for the loading of the K-Framework
 	 */
 	public class KfLoader extends EventDispatcher 
 	{
		protected static const KF_APPLICATION_CLASS_NAME : String = 'com.kusiri.kframework.KfApplication';
		
		protected var _configuration : XML;
		protected var _callback : Function;
		
        /**
         * Load and initialize the K-Framework
         * @param configuration Either an XML object or a URL
         */
        public function load(configuration: *, callback : Function) : void
        {
        	_callback = callback;
        	
        	if (configuration is XML)
        	{
        		_configuration = configuration;
        		loadFramework();
        		return;
        	}
        	
			var loader:URLLoader = new URLLoader();
			var request:URLRequest = new URLRequest(configuration);
			
			loader.addEventListener(Event.COMPLETE,
			
				function (event:Event):void
				{
				    var loader:URLLoader = event.target as URLLoader;
				   	_configuration = new XML(loader.data);
        			loadFramework();
				}
			);
			
			loader.load(request);

        }
        
        protected function loadFramework() : void
        {
        	
        	// check to see if we are developing
        	if (ApplicationDomain.currentDomain.hasDefinition(KF_APPLICATION_CLASS_NAME))
        	{
        		createApplication();
        		return;
        	} 

//			var kfUrl : String = configuration.framework[0].........
//
//            var ldr:Loader = new Loader();
//            var req:URLRequest = new URLRequest(kfUrl);
//            var ldrContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
//            ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
//            ldr.load(req, ldrContext);            		
        }
        
        private function createApplication(event:Event=null) : void
        {
        	var clazz : Class = ApplicationDomain.currentDomain.getDefinition(KF_APPLICATION_CLASS_NAME) as Class;
        	if (clazz == null) throw new Error('Cannot find class '+KF_APPLICATION_CLASS_NAME);
            var app : * = new clazz();
            app.initialize(_configuration, _callback);
        }

  	}
}